<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */



//数据舍入计算(返回不小于value能被10整除的下一个整数)
function kg_ceil_10($val)
{
	if ($val < 10) return 10;
	if ($val % 10 == 0) return $val;
   	return $val + (10 - ($val % 10));
}


//随机数
function kg_rand_string($len=6, $type='', $addChars='')
{
    $str = '';
    switch($type)
    {
        case 0:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 1:
            $chars = str_repeat('0123456789', 3);
            break;
        case 2:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
            break;
        case 3:
            $chars = 'abcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        default :
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
            break;
    }
    if($len > 10)
    {
        $chars = $type==1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
    }
    $chars = str_shuffle($chars);
    $str   = substr($chars, 0, $len);
    return $str;
}


//求字符串crc32值
function kg_crc32($str)
{
	return sprintf('%u', crc32($str));
}


//base64加解字符串
function kg_base64($str, $type='encode')
{
    $type = strtolower($type);
	return ($type == 'encode') ? str_replace('/', '$', base64_encode($str)) : base64_decode(str_replace('$', '/', $str));
}


//字符加解密
function kg_auth_code($string, $operation='decode', $key='', $expiry=0)
{
    $operation = strtolower($operation);
    $string = ($operation == 'decode') ? str_replace('$', '/', $string) : $string;
	$ckey_length = 4;
	$key = md5($key ? $key : get_site_config('site_auth_key'));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'decode' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'decode' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++)
	{
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	for($j = $i = 0; $i < 256; $i++)
	{
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	for($a = $j = $i = 0; $i < $string_length; $i++)
	{
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if($operation == 'decode')
	{
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16))
		{
			return substr($result, 26);
		}
		else
		{
			return '';
		}
	}
	else
	{
		$str = $keyc.str_replace('=', '', base64_encode($result));
		return str_replace('/', '$', $str);
	}
}


//用户密码加密salt
function kg_password_salt()
{
    return substr(md5(time().rand(1000,9999)), 8, 8);
}


//用户密码加密
function kg_password_encrypt($str, $salt)
{
    return md5(md5($str.$salt));
}


//截取字符串
function kg_substr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
    if(function_exists("mb_substr"))
    {
        return mb_substr($str, $start, $length, $charset);
    }
    elseif (function_exists('iconv_substr'))
    {
        return iconv_substr($str, $start, $length, $charset);
    }
    $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("", array_slice($match[0], $start, $length));
    return $suffix ? $slice.'...' : $slice;
}


//ip to country
function ip_to_country($ip)
{
    $url = 'http://api.hostip.info/get_html.php?ip='.$ip;
    return file_get_contents($url);
}


/**
 * @access public
 * @param array $list
 * @param mixed $condition array('name'=>$value) or name=$value
 * @return array
 */
function list_search($list, $condition) {
	if (empty($list))
	{
		return array();
	}
    if (is_string($condition)) 
    {
    	parse_str($condition, $condition);
    }
    $resultSet = array();
    foreach ($list as $key => $data)
    {
        $find = false;
        foreach ($condition as $field => $value)
        {
            if (isset($data[$field]))
            {
                if (0 === strpos($value, '/'))
                {
                    $find = preg_match($value, $data[$field]);
                }
                elseif ($data[$field] == $value)
                {
                    $find = true;
                }
            }
        }
        if ($find)
        {
        	$resultSet[] = &$list[$key];
        }
    }
    return $resultSet;
}


//取服务器IP
function get_server_ip()
{
    if (getenv('SERVER_ADDR'))
    {
    	$server_ip = getenv('SERVER_ADDR');
    }
    elseif (isset($_SERVER['SERVER_ADDR']))
    {
        $server_ip = $_SERVER['SERVER_ADDR'];
    }
    else
    {
        $server_ip = '0.0.0.0';
    }
    return $server_ip;
}


function get_client_ip()
{
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
   {
       $ip = getenv("HTTP_CLIENT_IP");
   }
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
   {
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   }
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
   {
       $ip = getenv("REMOTE_ADDR");
   }
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
   {
       $ip = $_SERVER['REMOTE_ADDR'];
   }
   else
   {
       $ip = "unknown";
   }
   return $ip;
}


function byte_format($size, $dec=2)
{
	$pos = 0;
	$a = array("B", "KB", "MB", "GB", "TB", "PB");
	while ($size >= 1024)
	{
        $size /= 1024;
		$pos++;
	}
	return round($size, $dec)." ".$a[$pos];
}


/**
 * 日期验证
 *
 * @param string $date (YYYY-MM-DD)
 * @param string $separator
 * @return bool
 */
function is_valid_date($date, $separator='-')
{
	$date = explode($separator, $date);
	return checkdate($date[1], $date[2], $date[0]);
}


//检查IP合法性
function validate_ip($ip)
{
    $ipv4 = filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV4);
    $ipv6 = filter_var($ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6);
    return $ipv4 || $ipv6;
}


//检查EMAIL合法性
function validate_email($email)
{
	$email = filter_var($email, FILTER_VALIDATE_EMAIL);
	return $email;
}


//用户名验证
function is_valid_username($username)
{
	$length = strlen(trim($username));
	$min_username_chars = get_site_config('min_username_chars');
	$max_username_chars = get_site_config('max_username_chars');
	$username_allowed_chars = get_site_config('username_allowed_chars');
	$blacklist = F('cache_username_blacklist');
	
	if($length > $max_username_chars || $length < $min_username_chars)
	{
		return 'username_invalid_length';
	}
	switch (strtolower($username_allowed_chars))
	{
		case 'char_any':
			$regex = '.+';
		break;
		case 'char_alpha_only':
			$regex = '[A-Za-z0-9]+';
		break;
		case 'char_alpha_spacer':
			$regex = '[A-Za-z0-9-_+ ]+';
		break;
	}
	if (!preg_match('/^'. $regex .'$/u', $username))
	{
		return 'username_invalid_chars';
	}
	if (!empty($blacklist))
	{
		if (preg_match('/'. $blacklist .'/', $username))
		{
			return 'username_disallowed';
		}
	}
	
	$map = array('username' => $username);
	$count = M('User')->where($map)->count();
	if ($count >= 1)
	{
		return 'username_taken';
	}
	return true;
}


//密码验证
function is_valid_password($password)
{
	$length = strlen(trim($password));
	$min_pwd_chars = get_site_config('min_pwd_chars');
	$max_pwd_chars = get_site_config('max_pwd_chars');
	$pwd_complex   = get_site_config('pwd_complex');
	
	$upper  = '[A-Z]';
	$lower  = '[a-z]';
	$letter = '[a-zA-Z]';
	$number = '[0-9]';
	$symbol = '[^A-Za-z0-9]';
	$chars  = array();
	
	if($length > $max_pwd_chars || $length < $min_pwd_chars)
	{
		return 'password_invalid_length';
	}
	switch (strtolower($pwd_complex))
	{
		case 'char_case':
			$chars[] = $lower;
			$chars[] = $upper;
		break;
		case 'char_alpha':
			$chars[] = $letter;
			$chars[] = $number;
		break;
		case 'char_symbol':
			$chars[] = $lower;
			$chars[] = $upper;
			$chars[] = $letter;
			$chars[] = $symbol;
		break;
	}
	foreach ($chars as $char)
	{
		if (!preg_match('/'. $char .'/u', $password))
		{
			return 'password_invalid_chars';
		}
	}
	return true;
}


//邮箱验证
function is_valid_email($email)
{
	$blacklist = F('cache_email_blacklist');
	
	if(strlen($email) < 6 || !preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email))
	{
		return 'email_invalid';
	}
	if (get_site_config('email_check_mx_enable'))
	{
		list($username, $domain) = explode('@', $email);
		if (kg_checkdnsrr($domain, 'A') === false || kg_checkdnsrr($domain, 'MX') === false)
		{
			return 'email_no_mx_record';
		}
	}
	if (!empty($blacklist))
	{
		if (preg_match('/'. $blacklist .'/i', $email))
		{
			return 'email_disallowed';
		}			
	}
	
	$map = array('email' => $email);
	$count = M('User')->where($map)->count();
	if ($count >= 1)
	{
		return 'email_taken';
	}
	return true;
}


//IP验证
function is_valid_ip($ip)
{
	$blacklist = F('cache_ip_blacklist');
    return preg_match('/'. $blacklist .'/', $ip) ? false : true;
}


/**
* Wrapper for php's checkdnsrr function.
*
* @param string $host	Fully-Qualified Domain Name
* @param string $type	Resource record type to lookup
*						Supported types are: MX (default), A, AAAA, NS, TXT, CNAME
*						Other types may work or may not work
*
* @return mixed		true if entry found,
*					false if entry not found,
*					null if this function is not supported by this environment
*
* Since null can also be returned, you probably want to compare the result
* with === true or === false,
*
* @author bantu
*/
function kg_checkdnsrr($host, $type = 'MX')
{
	// The dot indicates to search the DNS root (helps those having DNS prefixes on the same domain)
	if (substr($host, -1) == '.')
	{
		$host_fqdn = $host;
		$host = substr($host, 0, -1);
	}
	else
	{
		$host_fqdn = $host . '.';
	}
	// $host		has format	some.host.example.com
	// $host_fqdn	has format	some.host.example.com.

	// If we're looking for an A record we can use gethostbyname()
	if ($type == 'A' && function_exists('gethostbyname'))
	{
		return (@gethostbyname($host_fqdn) == $host_fqdn) ? false : true;
	}

	// checkdnsrr() is available on Windows since PHP 5.3,
	// but until 5.3.3 it only works for MX records
	// See: http://bugs.php.net/bug.php?id=51844

	// Call checkdnsrr() if 
	// we're looking for an MX record or
	// we're not on Windows or
	// we're running a PHP version where #51844 has been fixed

	// checkdnsrr() supports AAAA since 5.0.0
	// checkdnsrr() supports TXT since 5.2.4
	if (
		($type == 'MX' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.3', '>=')) &&
		($type != 'AAAA' || version_compare(PHP_VERSION, '5.0.0', '>=')) &&
		($type != 'TXT' || version_compare(PHP_VERSION, '5.2.4', '>=')) &&
		function_exists('checkdnsrr')
	)
	{
		return checkdnsrr($host_fqdn, $type);
	}

	// dns_get_record() is available since PHP 5; since PHP 5.3 also on Windows,
	// but on Windows it does not work reliable for AAAA records before PHP 5.3.1

	// Call dns_get_record() if 
	// we're not looking for an AAAA record or
	// we're not on Windows or
	// we're running a PHP version where AAAA lookups work reliable
	if (
		($type != 'AAAA' || DIRECTORY_SEPARATOR != '\\' || version_compare(PHP_VERSION, '5.3.1', '>=')) &&
		function_exists('dns_get_record')
	)
	{
		// dns_get_record() expects an integer as second parameter
		// We have to convert the string $type to the corresponding integer constant.
		$type_constant = 'DNS_' . $type;
		$type_param = (defined($type_constant)) ? constant($type_constant) : DNS_ANY;

		// dns_get_record() might throw E_WARNING and return false for records that do not exist
		$resultset = @dns_get_record($host_fqdn, $type_param);

		if (empty($resultset) || !is_array($resultset))
		{
			return false;
		}
		else if ($type_param == DNS_ANY)
		{
			// $resultset is a non-empty array
			return true;
		}

		foreach ($resultset as $result)
		{
			if (
				isset($result['host']) && $result['host'] == $host && 
				isset($result['type']) && $result['type'] == $type
			)
			{
				return true;
			}
		}

		return false;
	}

	// If we're on Windows we can still try to call nslookup via exec() as a last resort
	if (DIRECTORY_SEPARATOR == '\\' && function_exists('exec'))
	{
		@exec('nslookup -type=' . escapeshellarg($type) . ' ' . escapeshellarg($host_fqdn), $output);
		// If output is empty, the nslookup failed
		if (empty($output))
		{
			return NULL;
		}

		foreach ($output as $line)
		{
			$line = trim($line);
			if (empty($line))
			{
				continue;
			}

			// Squash tabs and multiple whitespaces to a single whitespace.
			$line = preg_replace('/\s+/', ' ', $line);

			switch ($type)
			{
				case 'MX':
					if (stripos($line, "$host MX") === 0)
					{
						return true;
					}
				break;
				case 'NS':
					if (stripos($line, "$host nameserver") === 0)
					{
						return true;
					}
				break;
				case 'TXT':
					if (stripos($line, "$host text") === 0)
					{
						return true;
					}
				break;
				case 'CNAME':
					if (stripos($line, "$host canonical name") === 0)
					{
						return true;
					}
				default:
				case 'A':
				case 'AAAA':
					if (!empty($host_matches))
					{
						// Second line
						if (stripos($line, "Address: ") === 0)
						{
							return true;
						}
						else
						{
							$host_matches = false;
						}
					}
					else if (stripos($line, "Name: $host") === 0)
					{
						// First line
						$host_matches = true;
					}
				break;
			}
		}
		return false;
	}
	return NULL;
}


//根据积分范围判定所属用户组,存在相关的组则返回该组ID,否则返回系统注册用户组
function identify_group_by_points($points)
{
	$group = 0;
	$Model = M('UserGroup');
	$map = array(
		'type' => 'member',
		'point_lower'  => array('neq', 0),
		'point_higher' => array('neq', 0),
	);
	$groups = $Model->where($map)->select();
	if ($groups)
	{
		foreach ($groups as $value)
		{
			if ($value['point_lower'] < $points && $points < $value['point_higher'])
			{
				$group = $value['group_id'];
				break;
			}
		}
	}
	return $group ? $group : 7;
}


//获取站点配置
function get_site_config($name)
{
	$configs = F('cache_site_configs');
	return isset($configs[$name]) ? $configs[$name] : NULL;
}


//获取站点域名
function get_site_domain()
{
    $protocol = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off' ? 'https://' : 'http://';
	$host = trim($_SERVER['HTTP_HOST'], '/');
	$port = $_SERVER['SERVER_PORT'] != 80 ? ':' . $_SERVER['SERVER_PORT'] : '';
	$domain = $protocol . $host . $port;
	return $domain;
}


//取得语言种类
function get_site_languages()
{
	$languages = array();
	$handle = dir(LANG_PATH);
	while (false !== ($entry = $handle->read()))
	{
		if (is_dir(LANG_PATH.$entry) && !in_array($entry, array('.', '..')))
		{
			$languages[$entry] = $entry;
		}
	}
	$handle->close();
	return $languages;
}


//取得主题种类
function get_site_themes()
{
    $themes = array();
	$handle = dir(TMPL_PATH);
	while (false !== ($entry = $handle->read()))
	{
		if (is_dir(TMPL_PATH.$entry) && !in_array($entry, array('.', '..')))
		{
			$themes[$entry] = $entry;
		}
	}
	$handle->close();
	return $themes;
}


//取得操作积分
function get_activity_points($code)
{
	$policy = unserialize(get_site_config('point_policy'));
	return intval($policy[$code]);
}


//取得用户组成员数
function get_group_user_count($group_id, $type='user_group')
{
    $type = ('user_group' != $type) ? $where = array('admin_group' => $group_id) : $where = array('user_group' => $group_id);
    return M('User')->where($where)->count();
}


//取得用户分组名
function get_group_name($group_id)
{
	$file = F('cache_usergroup_'.$group_id);
	return isset($file['name']) ? $file['name'] : NULL;
}


//取得分类名
function get_category_name($category_id)
{
	$file = F('cache_categories');
	return isset($file[$category_id]['name']) ? $file[$category_id]['name'] : NULL;
}


//判断是否是终极分类
function is_ultimate_category($category_id)
{
	$result =true;
	$categories = F('cache_categories');
	foreach ($categories as $key => $value)
	{
		if ($category_id == $categories[$key]['parent'])
		{
			$result = false;
			break;
		}
	}
	return $result;
}


//取得分类全路径URL
function get_category_path($category_id, $target='_self')
{
	$path = $seperator = '';
    $arr = F('cache_categories');
    if (empty($category_id) || !isset($arr[$category_id]))
    {
        return $path;
    }
    $category_path = explode(',', $arr[$category_id]['path']);
    foreach ($category_path as $value)
    {
    	$path .= $seperator.'<a href="'.format_category_url($arr[$value]['category_id']).'" target="'.$target.'">'.$arr[$value]['name'].'</a>';
    	$seperator = '&nbsp;&gt;&nbsp;';
    }
    return $path;
}


/**
 * 取得上级分类ID
 *
 * @param integer $category_id 分类ID
 * @return array 上级分类ID数组
 */
function get_parent_category_ids($category_id)
{
    $categories = F('cache_categories');
	$result = $categories[$category_id];
	return explode(',', substr($result['path'], 0, strrpos($result['path'], ',')));
}


/**
 * 取得下级分类ID

 * @param integer $category_id 分类ID
 * @param integer $self 是否包含父分类
 * @param integer $direct 是否直系下级
 * @param integer $level 分类层级
 * @return array
 */
function get_sub_category_ids($category_id, $self=0, $direct=0, $level=3)
{
    $ids = $self ? array($category_id) : array();
    $categories = F('cache_categories');
    foreach ($categories as $key => $value)
    {
        if (0 == $direct)
        {
            $path = ','.$value['path'].',';
        	if (false !== strpos($path, ','.$category_id.',') && $value['level'] <= $level && $category_id != $value['category_id'])
        	{
        		$ids[] = intval($value['category_id']);
        	}
        }
    	else
    	{
    	   if ($value['parent'] == $category_id)
    	    {
    	    	$ids[] = intval($value['category_id']);
    	    }
    	}
    }
    return $ids;
}


//格式化时间(时间已本地化)
function format_date($timestamp='', $format='')
{
    $user = cookie('user');
	$format = $format ? $format : get_site_config('default_dateformat');
	$timezone = isset($user['timezone']) ? $user['timezone'] : get_site_config('default_timezone');
	$timestamp = $timestamp ? $timestamp : time();
	$timestamp += $timezone * 3600;
	return gmdate($format, $timestamp);
}


//格式化title
function format_title($title, $seperator='')
{
	$seperator = empty($seperator) ? get_site_config('url_word_seperator') : $seperator;
	$lang = strtolower(get_site_config('default_lang'));
	$title = str_replace(array(',',$seperator), ' ', $title);
	$title = str_replace(C('URL_PATHINFO_DEPR'), '', $title);
	if ('en-us' == $lang)
	{
		$title = preg_replace('/[^a-z A-Z0-9]/i', '', $title);
	}
	else
	{
		$search = array('\\', '/', '\'', '"', ';', ':', ',', '.', '?','!','{','}','[',']','#','$','%','^','&','*','(',')','-','=','~','`','<','>', '＇', '＂', '；', '：', '，', '．', '？','。');
		$title  = str_replace($search, '', $title);
	}
	$array = explode(' ', $title);
	$temp = array();
	foreach ($array as $value)
	{
		if(trim($value)) $temp[] = $value;
	}
	return strtolower(implode($seperator, $temp));
}


//格式化分类url
function format_category_url($category_id, $type='')
{
	$type = $type ? $type : get_site_config('url_format_type');
	$categories = F('cache_categories');
	$category   = isset($categories[$category_id]) ? $categories[$category_id] : array();
	$category['name'] = format_title($category['name']);
	switch (strtolower($type))
	{
		case 'advanced':
		    $site_url = get_site_config('site_url');
		    $index = (2 != C('URL_MODEL')) ? '/index.php' : '';
			$url = $site_url.$index.'/categories/'.$category_id.'/'.$category['name'].C('URL_HTML_SUFFIX');
			break;
		case 'classic':
		    $url = get_site_domain().U('Category/index', array('cid'=>$category_id,'name'=>$category['name']));
		    break;
		default:
		    $url = get_site_domain().U('Category/index', array('cid'=>$category_id));
			break;
	}
	return $url;
}


//格式化tag url
function format_tag_url($tag_id, $name='', $type='')
{
	$type = $type ? $type : get_site_config('url_format_type');
	$name = format_title($name);
	switch (strtolower($type))
	{
		case 'advanced':
		    $site_url = get_site_config('site_url');
		    $index = (2 != C('URL_MODEL')) ? '/index.php' : '';
			$url = $site_url.$index.'/tags/'.$tag_id.'/'.$name.C('URL_HTML_SUFFIX');
			break;
		case 'classic':
		    $url = get_site_domain().U('Tag/index', array('tid'=>$tag_id,'name'=>$name));
		    break;
		default:
		    $url = get_site_domain().U('Tag/index', array('tid'=>$tag_id));
			break;
	}
	return $url;
}


//格式化问题url
function format_question_url($question_id, $title='', $type='')
{
	$type = $type ? $type : get_site_config('url_format_type');
	$title = format_title($title);
	switch (strtolower($type))
	{
		case 'advanced':
		    $site_url = get_site_config('site_url');
		    $index = (2 != C('URL_MODEL')) ? '/index.php' : '';
			$url = $site_url.$index.'/questions/'.$question_id.'/'.$title.C('URL_HTML_SUFFIX');
			break;
		case 'classic':
		    $url = get_site_domain().U('Question/details', array('qid'=>$question_id,'title'=>$title));
		    break;
		default:
		    $url = get_site_domain().U('Question/details', array('qid'=>$question_id));
			break;
	}
	return $url;
}


//格式化用户url
function format_user_url($user_id, $name, $type='')
{
	$type = $type ? $type : get_site_config('url_format_type');
	$name = format_title($name);
	switch (strtolower($type))
	{
		case 'advanced':
		    $site_url = get_site_config('site_url');
		    $index = (2 != C('URL_MODEL')) ? '/index.php' : '';
			$url = $site_url.$index.'/users/'.$user_id.'/'.$name.C('URL_HTML_SUFFIX');
			break;
		case 'classic':
		    $url = get_site_domain().U('User/activity', array('uid'=>$user_id,'name'=>$name));
		    break;
		default:
		    $url = get_site_domain().U('User/activity', array('uid'=>$user_id));
			break;
	}
	return $url;
}


//格式化团队url
function format_team_url($team_id, $name, $type='')
{
	$type = $type ? $type : get_site_config('url_format_type');
	$name = format_title($name);
	switch (strtolower($type))
	{
		case 'advanced':
		    $site_url = get_site_config('site_url');
		    $index = (2 != C('URL_MODEL')) ? '/index.php' : '';
			$url = $site_url.$index.'/teams/'.$team_id.'/'.$name.C('URL_HTML_SUFFIX');
			break;
		case 'classic':
		    $url = get_site_domain().U('Team/activity', array('tid'=>$team_id,'name'=>$name));
		    break;
		default:
		    $url = get_site_domain().U('Team/activity', array('tid'=>$team_id));
			break;
	}
	return $url;
}


//格式化faq url
function format_faq_url($faq_id, $title, $type='')
{
	$type = $type ? $type : get_site_config('url_format_type');
	$title = format_title($title);
	switch (strtolower($type))
	{
		case 'advanced':
		    $site_url = get_site_config('site_url');
		    $index = (2 != C('URL_MODEL')) ? '/index.php' : '';
			$url = $site_url.$index.'/faqs/'.$faq_id.'/'.$title.C('URL_HTML_SUFFIX');
			break;
		case 'classic':
		    $url = get_site_domain().U('Faq/details', array('fid'=>$faq_id,'title'=>$title));
		    break;
		default:
		    $url = get_site_domain().U('Faq/details', array('fid'=>$faq_id));
			break;
	}
	return $url;
}


//格式化page url
function format_page_url($page_id, $title, $type='')
{
	$type = $type ? $type : get_site_config('url_format_type');
	$title = format_title($title);
	switch (strtolower($type))
	{
		case 'advanced':
		    $site_url = get_site_config('site_url');
		    $index = (2 != C('URL_MODEL')) ? '/index.php' : '';
			$url = $site_url.$index.'/pages/'.$page_id.'/'.$title.C('URL_HTML_SUFFIX');
			break;
		case 'classic':
		    $url = get_site_domain().U('Page/index', array('pid'=>$page_id,'title'=>$title));
		    break;
		default:
		    $url = get_site_domain().U('Page/index', array('pid'=>$page_id));
			break;
	}
	return $url;
}


//格式化公告 url
function format_announce_url($announce_id, $title, $type='')
{
	$type = !empty($type) ? $type : get_site_config('url_format_type');
	$title = format_title($title);
	switch (strtolower($type))
	{
		case 'advanced':
		    $site_url = get_site_config('site_url');
		    $index = (2 != C('URL_MODEL')) ? '/index.php' : '';
			$url = $site_url.$index.'/announcements/'.$announce_id.'/'.$title.C('URL_HTML_SUFFIX');
			break;
		case 'classic':
		    $url = get_site_domain().U('Announcement/index', array('aid'=>$announce_id,'title'=>$title));
		    break;
		default:
		    $url = get_site_domain().U('Announcement/index', array('aid'=>$announce_id));
			break;
	}
	return $url;
}


//广告标签解析
function parse_ad_load($identifier)
{
    $ads = F('cache_advertisements');
    if (isset($ads[$identifier]))
    {
        $location = $ads[$identifier];
        $key = array_rand($location['html_code']);
        return str_replace('{$ad}', $location['html_code'][$key], $location['template']);
    }
}


//faq标签解析
function parse_faq_load($identifier)
{
    $faqs = F('cache_faqs');
    if (isset($faqs[$identifier]))
    {
        $url = format_faq_url($faqs['faq_id'], $faqs[$identifier]);
        return '<a href="{$url}">'.$faqs[$identifier]['title'].'</a>';
    }
}


//markup标签解析
function parse_markup($text, $mode='')
{
	import('@.Util.MarkupParser');
	$mode = !empty($mode) ? $mode : get_site_config('markup_mode'); 
	switch (strtolower($mode))
	{
		case 'html':
			$text = Input::safeHtml($text);
		break;
		case 'bbcode':
			$text = MarkupParser::bbcode2html($text);
		break;
		case 'wiki':
			$text = MarkupParser::wiki2html($text);
		break;
		case 'markdown':
			$text = MarkupParser::markdown2html($text);
		break;
		case 'textarea':
			$text = htmlspecialchars($text);
		break;
	}
	return $text;
}


/* End of file common.php */
/* Location: ./App/Common/common.php */